<?php

namespace app\api\controller;

use app\api\model\DownloadLog;
use app\api\model\LangClassFile AS FileModel;
use app\api\model\OauthOrderClass;
use app\api\validate\Download;
use app\api\validate\Page;

class LangClassFile extends Base
{
    /**
     * 首页搜索
     * @return array
     * @throws \think\Exception\DbException
     */
    public function free()
    {
        $page = $data['page'] = input('page') ? input('page') : 1;
        $size = $data['size'] = input('size') ? input('size') : $this->pageSize;

        // 检测变量
        $validate = new Page();
        if (!$validate->check($data)) {
            return self::sendResult(102, [], $validate->getError());
        }

        $model = FileModel::freeList($page, $size);
        return self::sendResult(self::$okCode, $model);
    }

    /**
     * 获取课程下面的文件内容，通过班级id和课程类型，课件类型（视频1，音频2，学习资料课件下载3，学习资料随堂作业4）查找
     * @param $classId int 班级id
     * @return array
     * @throws \think\Exception\DbException
     */
    public function read($classId)
    {
        // 课程类型，默认语音课
        $courseType = input('courseType') ? input('courseType') : FileModel::COURSE_VOICE;
        // 文件类型，默认视频
        $voice = FileModel::TYPE_VIDEO;
        $type = input('type') ? input('type') : $voice;
        $page = $data['page'] = input('page') ? input('page') : 1;
        $size = $data['size'] = input('size') ? input('size') : $this->pageSize;

        if ($classId <= 0) {
            return self::sendResult(100);
        }

        // 检测变量
        $validate = new Page();
        if (!$validate->check($data)) {
            return self::sendResult(102, [], $validate->getError());
        }

        $courseTypeArr = FileModel::attributes('course_type');
        if (!isset($courseTypeArr[$courseType])) {
            return self::sendResult(102, [], '课程类型错误');
        }

        $typeArr = FileModel::attributes('type');
        if (!isset($typeArr[$type])) {
            return self::sendResult(102, [], '文件类型错误');
        }

        $oauthId = $this->oauthInfo['id'];
        // 是否已经购买
        $buyLog = OauthOrderClass::getOneByClass($oauthId, $classId);
        // 不是视频，点击班级页面其他两个tab（音频、学习资料）判断是否购买，没购买不给点击
        if ($type != $voice) {
            if (empty($buyLog)) {
                return self::sendResult(109);
            }
        }

        $model = FileModel::getList($classId, $courseType, $type, $page, $size);
        // 返回是否已经购买
        $model['hasBuy'] = empty($buyLog) ? 0 : 1;
        return self::sendResult(self::$okCode, $model);
    }

    /**
     * 通过文件id获取文件路径，判断是否已经购买，购买则返回路径
     * @param int $fileId 文件id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function watch($fileId)
    {
        if ($fileId < 0) {
            return self::sendResult(100);
        }

        $oauthId = $this->oauthInfo['id'];
        // 判断文件是否可以观看
        $return = FileModel::canWatch($oauthId, $fileId);
        if (empty($return)) {
            return self::sendResult(102, [], '文件不存在');
        }
        if ($return['canWatch'] === false) {
            return self::sendResult(109);
        }
        return self::sendResult(self::$okCode, [
            'classId' => $return['classId'],
            'fileId' => $return['fileId'],
            'file' => $return['file'],
            'fileName' => $return['fileName'],
            'fileType' => $return['fileType'],
            'description' => $return['description'],
            'videoImg' => $return['videoImg'],
        ]);
    }

    /**
     * 通过文件id获取转码文件路径，判断是否已经购买，购买则返回路径
     * @param int $fileId 文件id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function transferWatch($fileId){
        if ($fileId < 0) {
            return self::sendResult(100);
        }
//        $type = input("type");
//        $oauthId = $this->oauthInfo['id'];
        $type = 2;
        $oauthId = 675;
        // 判断文件是否可以观看
        $return = FileModel::canTransferWatch($oauthId, $fileId,$type);
        dump($return);exit;
        if (empty($return)) {
            return self::sendResult(102, [], '文件不存在');
        }
        if ($return['canWatch'] === false) {
            return self::sendResult(109);
        }
        return self::sendResult(self::$okCode, [
            'classId' => $return['classId'],
            'fileId' => $return['fileId'],
            'file' => $return['file'],
            'fileType' => $return['fileType'],
            'description' => $return['description'],
            'videoImg' => $return['videoImg'],
        ]);
    }




    /**
     * 发送邮件
     * @param $fileId
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function download($fileId)
    {
        $email = input('email');
        if ($fileId < 0) {
            return self::sendResult(100);
        }

        if (empty($email)) {
            return self::sendResult(100, [], '邮件地址不能为空');
        }

        // 检测变量
        $validate = new Download();
        if (!$validate->check(['email' => $email])) {
            return self::sendResult(102, [], $validate->getError());
        }

        $oauthId = $this->oauthInfo['id'];
        // 判断文件是否可以观看
        $return = FileModel::canWatch($oauthId, $fileId);
        if (empty($return)) {
            return self::sendResult(102, [], '文件不存在');
        }
        if ($return['canWatch'] === false) {
            return self::sendResult(109);
        }

        if (!in_array($return['fileType'], [FileModel::TYPE_CLASS_FILE, FileModel::TYPE_HOMEWORK])) {
            return self::sendResult(102, [], '下载文件类型错误');
        }

        // 判断半小时之前是否下载过这个课件
        $log = DownloadLog::getOne($oauthId, $fileId);
        if ($log) {
            if (($log['create_time'] + 1800) > time()) {
                return self::sendResult(139);
            }
        }
        $res = DownloadLog::download($oauthId, $fileId, $return['file'], $email);
        $code = 140;
        $msg = '发送失败，请稍后再试';
        if ($res === true) {
            $code = self::$okCode;
            $msg = '发送成功';
        }
        return self::sendResult($code, [], $msg);
    }
}